package com.issoft.studentresitor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.issoft.studentresitor.domain.dto.UserDTO;
import com.issoft.studentresitor.domain.pojo.Student;
import com.issoft.studentresitor.domain.pojo.User;
import com.issoft.studentresitor.domain.vo.UserVo;
import com.issoft.studentresitor.mapper.StudentMapper;
import com.issoft.studentresitor.mapper.UserMapper;
import com.issoft.studentresitor.service.IUserService;
import com.issoft.studentresitor.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public UserVo login(UserDTO userDTO) {
        // 对前端传入的密码进行MD5加密（与注册时保持一致）
        String encryptedPassword = DigestUtil.md5Hex(userDTO.getPassword());
        // 创建新的DTO对象存储加密后的密码，避免修改原DTO
        UserDTO encryptedDTO = new UserDTO();
        encryptedDTO.setUsername(userDTO.getUsername());
        encryptedDTO.setPassword(encryptedPassword);

        // 使用加密后的密码查询用户
        User user = userMapper.login(encryptedDTO);

        // 如果用户不存在，直接返回null（controller层会处理错误提示）
        if (user == null) {
            return null;
        }

        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("username", user.getUsername());
        String token = JwtUtils.generateToken(claims);

        // 返回包含token的UserVo（注意：不要返回密码，避免安全问题）
        return new UserVo(user.getUserId(), user.getUsername(), null, user.getRole(), token);
    }

    @Autowired
    private UserMapper userMapper;
    @Override
    public void insertUser(User user) {
        log.info("插入用户：{}", user);
        //加密密码使用hutools的md5加密
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        userMapper.insertUser(user);
    }
    //修改密码
    @Override
    public int updatePassword(UserDTO userDTO) {
        log.info("修改密码：{}", userDTO);
        //先进行原来的账号密码查询有数据才能修改
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", DigestUtil.md5Hex(userDTO.getPassword()));
        User oldUser = userMapper.selectOne(queryWrapper);
        if (oldUser != null) {
            //加密密码使用hutools的md5加密
            userDTO.setPassword(DigestUtil.md5Hex(userDTO.getNewPassword()));
            return userMapper.updatePassword(userDTO);
        }
        log.error("修改密码失败：用户不存在");
        return 0;
    }

    @Override
    public List<User> queryNoUserIdStu() {
        return userMapper.queryNoUserIdStu();
    }

    @Override
    public int updatePasswordByUserId(Integer userId, String password) {
        return userMapper.updatePasswordByUserId(userId, DigestUtil.md5Hex(password));
    }
}
